package com.lyc.campuslife.interceptor;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.lyc.campuslife.dto.UserDTO;
import com.lyc.campuslife.utils.RedisConstants;
import lombok.extern.slf4j.Slf4j;
import org.redisson.client.RedisTimeoutException;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import static com.lyc.campuslife.utils.HttpRequestConstants.AUTH;
import static com.lyc.campuslife.utils.HttpRequestConstants.USER_INFO;

@Slf4j
public class RefreshTokenInterceptor implements HandlerInterceptor {
    private StringRedisTemplate stringRedisTemplate;
    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            // 1 获取请求头中的token
            String token = request.getHeader(AUTH);
            if (StrUtil.isBlank(token)) {
                return true;
            }
            // 2 获取redis中的用户
            Map<Object, Object> userMap = stringRedisTemplate.opsForHash().entries(RedisConstants.LOGIN_USER_KEY + token);
            // 3 判断用户是否存在
            if (userMap.isEmpty()) {
                return true;
            }
            // 4 将查询到的hash数据转为DTO对象
            UserDTO userDTO = BeanUtil.fillBeanWithMap(userMap, new UserDTO(), false);
            // 5 存在 保存用户信息到ThreadLocal
//            request.setAttribute("userDTO",userDTO);
//            UserHolder.saveUser(userDTO)
            request.setAttribute(USER_INFO,userDTO);
            // 6 刷新token有效期
            stringRedisTemplate.expire(RedisConstants.LOGIN_USER_KEY + token, RedisConstants.LOGIN_USER_TTL, TimeUnit.MINUTES);
        } catch (RedisConnectionFailureException | RedisTimeoutException e) {
            // 记录异常信息
            log.error("Redis service is unavailable", e);
            // 设置错误响应
            response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            response.getWriter().write("Service unavailable, please try again later.");
            // 不继续执行拦截器链
            return false;
        } catch (Exception e) {
            // 记录其他异常信息
            log.error("An unexpected error occurred", e);
            // 设置错误响应
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            response.getWriter().write("Internal server error, please contact support.");
            // 不继续执行拦截器链
            return false;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
//        UserHolder.removeUser();
    }
}
